import { useState, useEffect, useContext  } from "react";
import { NavBar, List, Button, Checkbox, Toast, InfiniteScroll } from "antd-mobile";
import { useHistory, useRouteMatch } from 'react-router-dom';

import { ConversationType } from "../../../constants";
import AvatarImage from "../../../components/AvatarImage";
import { MySdkStoreContext } from '../../../context';

import "./style.scss";

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const { params: { groupId } } = useRouteMatch();
  const [list, setList] = useState([]);
  const [pagination, setPagination] = useState({ pageIndex: 1, totalPage: 1, totalItemCount: 0 });
  const [selectedItem, setSelectedItem] = useState([]);

  const getList = async (pageIndex) => {
    const data = await mySdkStore.sdk.queryConversationList({ type: 'all', pageIndex });
    const { list: rows = [], currentPageIndex, totalItemCount, totalPage } = data;
    setList([...list, ...rows]);
    setPagination({ pageIndex: currentPageIndex, totalItemCount, totalPage });
  }

  useEffect(() => {
    getList(1);
  }, []);

  const handleSearch = () => {

  }

  const handleAddToGroup = async () => {
    // todo: api只支持单条
    const cid = selectedItem[0];
    try {
      await mySdkStore.sdk.addConversationToGroups({ cid, groupId });
      history.goBack();
      Toast.show('添加成功');
    } catch (e: any) {
      console.log(e);
      Toast.show(e.errorMessage)
    }
  }

  return (<div className="chooseConvertPage">
      <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>选择会话</NavBar>
      {/* todo: queryConversationList 没有关键词搜索参数 */}
      {/* <SearchBar style={{ '--background': '#ffffff', margin: 12 }} placeholder="搜索" onSearch={() => handleSearch()} /> */}
        <Checkbox.Group onChange={(val) => setSelectedItem(val)}>
          <List>
            {list.map(item => <List.Item
            key={item.cid}
            prefix={
            <>
              <Checkbox value={item.cid} style={{ marginRight: 12, marginBottom: 10 }} />
              <AvatarImage
                src={item.sessionLogoUrl}
                style={{ display: 'inline-block', borderRadius: 8 }}
                fit='cover'
                width={36}
                height={36}
                userName={item.type === ConversationType.Single ? item.sessionName : ''}
                groupName={item.type === ConversationType.Group ? item.sessionName : ''}
              />
          </>}>{item.sessionName}</List.Item>)}
        </List>
        <InfiniteScroll loadMore={() => getList(pagination.pageIndex + 1)} hasMore={pagination.totalPage > pagination.pageIndex} />
      </Checkbox.Group>
      <div className="btnArea">
        已选择：{selectedItem.length}人
        <Button style={{ float: 'right' }} onClick={handleAddToGroup} color="primary" size="small">确定</Button>
      </div>
  </div>
  )
}